const connection = require('../app/database')

class SettingService {
	async create({ carouselName, image_url, status = 'active' }) {
		const statement =
			'INSERT INTO carousel(name, image_url, status) VALUES (?,?,?)'
		const [result] = await connection.execute(statement, [
			carouselName,
			image_url,
			status
		])
		return result
	}

	async remove(carousel_id) {
		const statement = `
      DELETE FROM carousel WHERE id = ?
    `
		const [result] = await connection.execute(statement, [carousel_id])
		return result
	}

	async updateStatus(carousel_id, status) {
		const statement = `
      UPDATE carousel SET status = ? WHERE id = ?
    `
		const [result] = await connection.execute(statement, [status, carousel_id])
		return result
	}

	async getCarousels(carouselName, status, limit = 10, offset = 0) {
		const params = []
		let baseQuery = `
      SELECT * FROM carousel WHERE 1=1
    `
		let countQuery = `
      SELECT count(*) as count FROM carousel WHERE 1=1
    `
		if (carouselName) {
			baseQuery = baseQuery + 'AND name LIKE ? '
			countQuery = countQuery + 'AND name LIKE ? '
			params.push(`%${carouselName}%`)
		}
		if (status) {
			baseQuery = baseQuery + 'AND status = ? '
			countQuery = countQuery + 'AND status = ? '
			params.push(status)
		}
		baseQuery = baseQuery + `LIMIT ${limit} OFFSET ${offset}`
		const [result] = await connection.execute(baseQuery, params)
		const [count] = await connection.execute(countQuery, params)
		return {
			totalCount: count[0].count,
			list: result
		}
	}
}

module.exports = new SettingService()
